// 本地PVP游戏逻辑
class LocalPVPGame {
    constructor() {
        // 游戏配置
        this.gridSize = 20;
        this.canvasWidth = 800;
        this.canvasHeight = 600;
        this.gridWidth = this.canvasWidth / this.gridSize;
        this.gridHeight = this.canvasHeight / this.gridSize;
        
        // 游戏状态
        this.gameRunning = false;
        this.gamePaused = false;
        this.gameOver = false;
        
        // 游戏时间设置（2分钟）
        this.gameDuration = 2 * 60 * 1000; // 2分钟（毫秒）
        this.startTime = 0;
        this.elapsedTime = 0;
        this.gameSpeed = 15; // 降低游戏速度，数值越大速度越慢
        
        // 玩家蛇配置
        this.player1 = {
            body: [],
            direction: { x: 1, y: 0 },
            nextDirection: { x: 1, y: 0 },
            color: '#4facfe',
            headColor: '#00a8ff',
            score: 0,
            speed: 5,
            isAlive: true
        };
        
        this.player2 = {
            body: [],
            direction: { x: -1, y: 0 },
            nextDirection: { x: -1, y: 0 },
            color: '#ff6b6b',
            headColor: '#ff3838',
            score: 0,
            speed: 5,
            isAlive: true
        };
        
        // 食物配置（中等模式：三种食物）
        this.foods = {
            normal: { position: null, color: '#28a745', points: 1, type: 'normal' },
            normal2: { position: null, color: '#20c997', points: 1, type: 'normal2' },
            golden: { position: null, color: '#ffd700', points: 3, type: 'golden' },
            moving: { position: null, color: '#e83e8c', points: 2, type: 'moving', direction: { x: 1, y: 0 } }
        };
        
        // 移动食物速度
        this.movingFoodSpeed = 3;
        this.movingFoodCounter = 0;
        
        // DOM元素
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.timerDisplay = document.getElementById('timer');
        this.player1ScoreDisplay = document.getElementById('player1-score');
        this.player2ScoreDisplay = document.getElementById('player2-score');
        this.gameOverlay = document.getElementById('gameOverlay');
        this.gameResult = document.getElementById('gameResult');
        
        // 按钮事件
        this.setupEventListeners();
        
        // 初始化游戏
        this.init();
    }
    
    init() {
        // 初始化玩家蛇
        this.initializeSnakes();
        
        // 生成食物
        this.generateAllFoods();
        
        // 显示开始界面
        this.showStartScreen();
    }
    
    initializeSnakes() {
        // 玩家1（左侧）初始位置
        const player1StartX = Math.floor(this.gridWidth / 4);
        const player1StartY = Math.floor(this.gridHeight / 2);
        
        this.player1.body = [
            { x: player1StartX, y: player1StartY },
            { x: player1StartX - 1, y: player1StartY },
            { x: player1StartX - 2, y: player1StartY }
        ];
        
        // 玩家2（右侧）初始位置
        const player2StartX = Math.floor(this.gridWidth * 3 / 4);
        const player2StartY = Math.floor(this.gridHeight / 2);
        
        this.player2.body = [
            { x: player2StartX, y: player2StartY },
            { x: player2StartX + 1, y: player2StartY },
            { x: player2StartX + 2, y: player2StartY }
        ];
        
        // 重置方向和状态
        this.player1.direction = { x: 1, y: 0 };
        this.player1.nextDirection = { x: 1, y: 0 };
        this.player1.isAlive = true;
        this.player1.score = 0;
        
        this.player2.direction = { x: -1, y: 0 };
        this.player2.nextDirection = { x: -1, y: 0 };
        this.player2.isAlive = true;
        this.player2.score = 0;
    }
    
    generateAllFoods() {
        // 生成普通食物
        this.generateFood('normal');
        this.generateFood('normal2');
        
        // 生成金色食物
        this.generateFood('golden');
        
        // 生成移动食物
        this.generateFood('moving');
        this.foods.moving.direction = { 
            x: Math.random() > 0.5 ? 1 : -1, 
            y: Math.random() > 0.5 ? 1 : -1 
        };
    }
    
    generateFood(type) {
        let position;
        let attempts = 0;
        const maxAttempts = 100;
        
        do {
            position = {
                x: Math.floor(Math.random() * this.gridWidth),
                y: Math.floor(Math.random() * this.gridHeight)
            };
            attempts++;
        } while (
            this.isPositionOccupied(position) && attempts < maxAttempts
        );
        
        if (attempts < maxAttempts) {
            this.foods[type].position = position;
        }
    }
    
    isPositionOccupied(position) {
        // 检查是否与蛇身重叠
        for (const segment of this.player1.body) {
            if (segment.x === position.x && segment.y === position.y) return true;
        }
        for (const segment of this.player2.body) {
            if (segment.x === position.x && segment.y === position.y) return true;
        }
        
        // 检查是否与其他食物重叠
        for (const foodType in this.foods) {
            const food = this.foods[foodType];
            if (food.position && food.position.x === position.x && food.position.y === position.y) {
                return true;
            }
        }
        
        return false;
    }
    
    setupEventListeners() {
        // 键盘控制
        document.addEventListener('keydown', (e) => this.handleKeyPress(e));
        
        // 按钮事件
        document.getElementById('startBtn').addEventListener('click', () => this.startGame());
        document.getElementById('pauseBtn').addEventListener('click', () => this.togglePause());
        document.getElementById('restartBtn').addEventListener('click', () => this.restartGame());
        document.getElementById('backBtn').addEventListener('click', () => this.goBack());
        document.getElementById('playAgainBtn').addEventListener('click', () => this.restartGame());
        document.getElementById('backToMenuBtn').addEventListener('click', () => window.location.href = 'game-home.html');
        
        // 防止方向键滚动页面
        document.addEventListener('keydown', (e) => {
            if ([37, 38, 39, 40].includes(e.keyCode)) {
                e.preventDefault();
            }
        });
    }
    
    handleKeyPress(e) {
        if (!this.gameRunning || this.gamePaused) return;
        
        // 玩家1控制（WASD）
        if (this.player1.isAlive) {
            switch(e.key.toLowerCase()) {
                case 'w':
                    if (this.player1.direction.y !== 1) this.player1.nextDirection = { x: 0, y: -1 };
                    break;
                case 's':
                    if (this.player1.direction.y !== -1) this.player1.nextDirection = { x: 0, y: 1 };
                    break;
                case 'a':
                    if (this.player1.direction.x !== 1) this.player1.nextDirection = { x: -1, y: 0 };
                    break;
                case 'd':
                    if (this.player1.direction.x !== -1) this.player1.nextDirection = { x: 1, y: 0 };
                    break;
            }
        }
        
        // 玩家2控制（方向键）
        if (this.player2.isAlive) {
            switch(e.keyCode) {
                case 38: // 上箭头
                    if (this.player2.direction.y !== 1) this.player2.nextDirection = { x: 0, y: -1 };
                    break;
                case 40: // 下箭头
                    if (this.player2.direction.y !== -1) this.player2.nextDirection = { x: 0, y: 1 };
                    break;
                case 37: // 左箭头
                    if (this.player2.direction.x !== 1) this.player2.nextDirection = { x: -1, y: 0 };
                    break;
                case 39: // 右箭头
                    if (this.player2.direction.x !== -1) this.player2.nextDirection = { x: 1, y: 0 };
                    break;
            }
        }
        
        // 空格键加速（两个玩家同时加速）
        if (e.keyCode === 32) {
            this.player1.speed = 12;
            this.player2.speed = 12;
        }
    }
    
    startGame() {
        this.gameRunning = true;
        this.gamePaused = false;
        this.gameOver = false;
        this.startTime = Date.now();
        
        // 隐藏开始界面
        this.gameOverlay.style.display = 'none';
        
        // 开始游戏循环
        this.gameLoop();
    }
    
    togglePause() {
        if (!this.gameRunning) return;
        
        this.gamePaused = !this.gamePaused;
        const pauseBtn = document.getElementById('pauseBtn');
        
        if (this.gamePaused) {
            pauseBtn.innerHTML = '<i class="bi bi-play-fill"></i> 继续';
            pauseBtn.classList.remove('btn-warning');
            pauseBtn.classList.add('btn-success');
        } else {
            pauseBtn.innerHTML = '<i class="bi bi-pause-fill"></i> 暂停';
            pauseBtn.classList.remove('btn-success');
            pauseBtn.classList.add('btn-warning');
            this.gameLoop();
        }
    }
    
    restartGame() {
        // 重置游戏状态
        this.gameRunning = false;
        this.gamePaused = false;
        this.gameOver = false;
        
        // 隐藏结果界面
        this.gameResult.classList.add('hidden');
        
        // 重新初始化游戏
        this.initializeSnakes();
        this.generateAllFoods();
        
        // 显示开始界面
        this.showStartScreen();
    }
    
    goBack() {
        window.location.href = 'duel-choose.html';
    }
    
    showStartScreen() {
        this.gameOverlay.style.display = 'flex';
        document.getElementById('overlayTitle').textContent = '本地PVP对决';
        document.getElementById('overlayMessage').textContent = '准备开始双人对战';
    }
    
    gameLoop() {
        if (!this.gameRunning || this.gamePaused) return;
        
        // 更新时间显示
        this.updateTimer();
        
        // 检查游戏结束条件
        if (this.checkGameEnd()) {
            this.endGame();
            return;
        }
        
        // 更新移动食物
        this.updateMovingFood();
        
        // 更新玩家蛇
        this.updatePlayer(this.player1);
        this.updatePlayer(this.player2);
        
        // 绘制游戏
        this.draw();
        
        // 继续游戏循环
        setTimeout(() => this.gameLoop(), 1000 / this.gameSpeed);
    }
    
    updateTimer() {
        this.elapsedTime = Date.now() - this.startTime;
        const remainingTime = Math.max(0, this.gameDuration - this.elapsedTime);
        const minutes = Math.floor(remainingTime / 60000);
        const seconds = Math.floor((remainingTime % 60000) / 1000);
        
        this.timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        
        // 时间到，游戏结束
        if (remainingTime <= 0) {
            this.gameOver = true;
        }
    }
    
    updateMovingFood() {
        if (!this.foods.moving.position) return;
        
        this.movingFoodCounter++;
        if (this.movingFoodCounter >= this.movingFoodSpeed) {
            this.movingFoodCounter = 0;
            
            const food = this.foods.moving;
            let newX = food.position.x + food.direction.x;
            let newY = food.position.y + food.direction.y;
            
            // 边界碰撞检测
            if (newX < 0 || newX >= this.gridWidth) {
                food.direction.x *= -1;
                newX = food.position.x + food.direction.x;
            }
            if (newY < 0 || newY >= this.gridHeight) {
                food.direction.y *= -1;
                newY = food.position.y + food.direction.y;
            }
            
            // 检查新位置是否被占用
            const newPosition = { x: newX, y: newY };
            if (!this.isPositionOccupied(newPosition)) {
                food.position = newPosition;
            } else {
                // 如果新位置被占用，改变方向
                food.direction.x = Math.random() > 0.5 ? 1 : -1;
                food.direction.y = Math.random() > 0.5 ? 1 : -1;
            }
        }
    }
    
    updatePlayer(player) {
        if (!player.isAlive) return;
        
        // 更新方向
        player.direction = { ...player.nextDirection };
        
        // 计算新头部位置
        const head = { ...player.body[0] };
        head.x += player.direction.x;
        head.y += player.direction.y;
        
        // 边界碰撞检测
        if (head.x < 0 || head.x >= this.gridWidth || head.y < 0 || head.y >= this.gridHeight) {
            player.isAlive = false;
            return;
        }
        
        // 自身碰撞检测
        for (let i = 0; i < player.body.length; i++) {
            if (head.x === player.body[i].x && head.y === player.body[i].y) {
                player.isAlive = false;
                return;
            }
        }
        
        // 对方蛇身碰撞检测
        const otherPlayer = player === this.player1 ? this.player2 : this.player1;
        if (otherPlayer.isAlive) {
            for (let i = 0; i < otherPlayer.body.length; i++) {
                if (head.x === otherPlayer.body[i].x && head.y === otherPlayer.body[i].y) {
                    player.isAlive = false;
                    return;
                }
            }
        }
        
        // 添加到头部
        player.body.unshift(head);
        
        // 检查是否吃到食物
        let ateFood = false;
        for (const foodType in this.foods) {
            const food = this.foods[foodType];
            if (food.position && head.x === food.position.x && head.y === food.position.y) {
                player.score += food.points;
                this.generateFood(foodType);
                ateFood = true;
                break;
            }
        }
        
        // 如果没有吃到食物，移除尾部
        if (!ateFood) {
            player.body.pop();
        }
        
        // 重置速度（如果之前加速了）
        player.speed = 8;
        
        // 更新分数显示
        this.updateScoreDisplay();
    }
    
    updateScoreDisplay() {
        this.player1ScoreDisplay.textContent = this.player1.score;
        this.player2ScoreDisplay.textContent = this.player2.score;
    }
    
    checkGameEnd() {
        // 时间到
        if (this.gameOver) return true;
        
        // 任意一方死亡就结束游戏
        if (!this.player1.isAlive || !this.player2.isAlive) return true;
        
        return false;
    }
    
    endGame() {
        this.gameRunning = false;
        
        // 计算游戏时长
        const totalTime = Math.min(this.elapsedTime, this.gameDuration);
        const minutes = Math.floor(totalTime / 60000);
        const seconds = Math.floor((totalTime % 60000) / 1000);
        
        // 确定获胜者
        let winner = '平局';
        let gameEndReason = '时间到';
        
        if (!this.player1.isAlive && !this.player2.isAlive) {
            gameEndReason = '双方都死亡';
            if (this.player1.score > this.player2.score) {
                winner = '玩家1 (WASD)';
            } else if (this.player2.score > this.player1.score) {
                winner = '玩家2 (方向键)';
            }
        } else if (!this.player1.isAlive) {
            gameEndReason = '玩家1死亡';
            winner = '玩家2 (方向键)';
        } else if (!this.player2.isAlive) {
            gameEndReason = '玩家2死亡';
            winner = '玩家1 (WASD)';
        } else if (this.player1.score > this.player2.score) {
            winner = '玩家1 (WASD)';
        } else if (this.player2.score > this.player1.score) {
            winner = '玩家2 (方向键)';
        }
        
        // 更新结果界面
        document.getElementById('finalPlayer1Score').textContent = this.player1.score;
        document.getElementById('finalPlayer2Score').textContent = this.player2.score;
        document.getElementById('gameDuration').textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        document.getElementById('winner').textContent = winner;
        document.getElementById('gameEndReason').textContent = gameEndReason;
        
        // 显示结果界面
        this.gameResult.classList.remove('hidden');
    }
    
    draw() {
        // 清空画布
        this.ctx.fillStyle = '#1a1a2e';
        this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
        
        // 绘制网格（可选）
        this.drawGrid();
        
        // 绘制食物
        this.drawFoods();
        
        // 绘制玩家蛇
        this.drawSnake(this.player1);
        this.drawSnake(this.player2);
        
        // 绘制游戏状态信息
        this.drawGameInfo();
    }
    
    drawGrid() {
        this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
        this.ctx.lineWidth = 1;
        
        // 绘制垂直线
        for (let x = 0; x <= this.canvasWidth; x += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.canvasHeight);
            this.ctx.stroke();
        }
        
        // 绘制水平线
        for (let y = 0; y <= this.canvasHeight; y += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.canvasWidth, y);
            this.ctx.stroke();
        }
    }
    
    drawFoods() {
        for (const foodType in this.foods) {
            const food = this.foods[foodType];
            if (food.position) {
                this.ctx.fillStyle = food.color;
                
                // 为移动食物添加动画效果
                if (foodType === 'moving') {
                    this.ctx.shadowBlur = 10;
                    this.ctx.shadowColor = food.color;
                }
                
                this.ctx.fillRect(
                    food.position.x * this.gridSize,
                    food.position.y * this.gridSize,
                    this.gridSize,
                    this.gridSize
                );
                
                // 重置阴影
                this.ctx.shadowBlur = 0;
                
                // 为金色食物添加星星效果
                if (foodType === 'golden') {
                    this.ctx.fillStyle = '#fff';
                    this.ctx.font = '12px Arial';
                    this.ctx.fillText('★', 
                        food.position.x * this.gridSize + this.gridSize / 3,
                        food.position.y * this.gridSize + this.gridSize / 1.5
                    );
                }
            }
        }
    }
    
    drawSnake(player) {
        if (!player.isAlive) return;
        
        // 绘制蛇身
        for (let i = 0; i < player.body.length; i++) {
            const segment = player.body[i];
            
            // 蛇头特殊处理
            if (i === 0) {
                this.ctx.fillStyle = player.headColor;
            } else {
                // 蛇身使用渐变色，让蛇身有层次感
                const gradient = this.ctx.createLinearGradient(
                    segment.x * this.gridSize, segment.y * this.gridSize,
                    segment.x * this.gridSize + this.gridSize, segment.y * this.gridSize + this.gridSize
                );
                gradient.addColorStop(0, this.lightenColor(player.color, 0.2));
                gradient.addColorStop(1, player.color);
                this.ctx.fillStyle = gradient;
            }
            
            // 绘制蛇身
            this.ctx.fillRect(
                segment.x * this.gridSize,
                segment.y * this.gridSize,
                this.gridSize,
                this.gridSize
            );
            
            // 只在蛇头绘制眼睛
            if (i === 0) {
                this.ctx.fillStyle = '#fff';
                const eyeSize = this.gridSize / 5;
                const eyeOffset = this.gridSize / 3;
                
                // 根据方向绘制眼睛位置
                if (player.direction.x === 1) { // 向右
                    this.ctx.fillRect(
                        segment.x * this.gridSize + this.gridSize - eyeOffset,
                        segment.y * this.gridSize + eyeOffset,
                        eyeSize, eyeSize
                    );
                    this.ctx.fillRect(
                        segment.x * this.gridSize + this.gridSize - eyeOffset,
                        segment.y * this.gridSize + this.gridSize - eyeOffset - eyeSize,
                        eyeSize, eyeSize
                    );
                } else if (player.direction.x === -1) { // 向左
                    this.ctx.fillRect(
                        segment.x * this.gridSize + eyeOffset - eyeSize,
                        segment.y * this.gridSize + eyeOffset,
                        eyeSize, eyeSize
                    );
                    this.ctx.fillRect(
                        segment.x * this.gridSize + eyeOffset - eyeSize,
                        segment.y * this.gridSize + this.gridSize - eyeOffset - eyeSize,
                        eyeSize, eyeSize
                    );
                } else if (player.direction.y === 1) { // 向下
                    this.ctx.fillRect(
                        segment.x * this.gridSize + eyeOffset,
                        segment.y * this.gridSize + this.gridSize - eyeOffset,
                        eyeSize, eyeSize
                    );
                    this.ctx.fillRect(
                        segment.x * this.gridSize + this.gridSize - eyeOffset - eyeSize,
                        segment.y * this.gridSize + this.gridSize - eyeOffset,
                        eyeSize, eyeSize
                    );
                } else { // 向上
                    this.ctx.fillRect(
                        segment.x * this.gridSize + eyeOffset,
                        segment.y * this.gridSize + eyeOffset - eyeSize,
                        eyeSize, eyeSize
                    );
                    this.ctx.fillRect(
                        segment.x * this.gridSize + this.gridSize - eyeOffset - eyeSize,
                        segment.y * this.gridSize + eyeOffset - eyeSize,
                        eyeSize, eyeSize
                    );
                }
            }
        }
    }
    
    drawGameInfo() {
        // 绘制玩家状态指示器
        if (!this.player1.isAlive) {
            this.ctx.fillStyle = 'rgba(255, 0, 0, 0.7)';
            this.ctx.font = 'bold 16px Arial';
            this.ctx.fillText('玩家1 死亡', 10, 20);
        }
        
        if (!this.player2.isAlive) {
            this.ctx.fillStyle = 'rgba(255, 0, 0, 0.7)';
            this.ctx.font = 'bold 16px Arial';
            this.ctx.fillText('玩家2 死亡', this.canvasWidth - 100, 20);
        }
        
        // 如果游戏暂停，显示暂停信息
        if (this.gamePaused) {
            this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
            this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
            
            this.ctx.fillStyle = '#fff';
            this.ctx.font = 'bold 36px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText('游戏暂停', this.canvasWidth / 2, this.canvasHeight / 2);
            this.ctx.textAlign = 'left';
        }
    }
    
    lightenColor(color, amount) {
        // 简单的颜色变亮函数
        const hex = color.replace('#', '');
        const num = parseInt(hex, 16);
        const r = Math.min(255, ((num >> 16) & 0xff) + amount * 255);
        const g = Math.min(255, ((num >> 8) & 0xff) + amount * 255);
        const b = Math.min(255, (num & 0xff) + amount * 255);
        
        return `rgb(${r}, ${g}, ${b})`;
    }
}

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', function() {
    new LocalPVPGame();
});